package com.zu.commu;

import com.zu.commu.context.ParseGPRSConf;
import com.zu.commu.context.ParseServerConf;
import com.zu.commu.context.ServerContext;
import com.zu.commu.dataSource.imp.pool.NcsDataSourceManager;
import com.zu.commu.exception.CommuException;
import com.zu.commu.local.LocalServer;
import com.zu.commu.remote.RemoteServer;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.io.File;
import java.net.URL;

public class CommuServer {
	private static long startTime;
	private static long endTime;

	public static void main(String[] args) {
		new CommuServer().startServer();
	}

	public void startServer() {
		startTime = System.currentTimeMillis();
		boolean needStartLocal = true;

		if (!initServer()) {
			System.out.println("服务器初始化失败，不能正常启动！");
			try {
				Thread.sleep(10000L);
			} catch (Exception localException) {
			}

		} else {
			new StartRemoteServerThread().start();

			if (ServerContext.fromCenterType.equalsIgnoreCase("servlet")) {
				needStartLocal = false;
				System.out.println("据服务器配置-不需要启动接收中心命令的服务！");
			}
			if (ServerContext.fromCenterType.equalsIgnoreCase("socket")) {
				new StartLocalServerThread().start();
			}

			boolean waitLocal = true;
			boolean waitRemote = true;
			while (true) {
				if ((needStartLocal)
						&& (!ServerContext.localServerStarted.booleanValue()))
					waitLocal = true;
				else {
					waitLocal = false;
				}
				if (!ServerContext.remoteServerStarted.booleanValue())
					waitRemote = true;
				else {
					waitRemote = false;
				}
				if ((!waitLocal) && (!waitRemote))
					break;
				try {
					Thread.sleep(100L);
				} catch (Exception localException1) {
				}
				continue;
			}

			if (ServerContext.GSMServerEnabled.booleanValue()) {
				System.out.println("开始启动短信服务...");
				new StartGSMServerThread().start();

				while (!ServerContext.GSMServerStarted.booleanValue()) {
					try {
						Thread.sleep(100L);
					} catch (Exception localException2) {
					}
					continue;
				}

			}

			endTime = System.currentTimeMillis();
			System.out
					.println("通信服务器 启动用时:" + (endTime - startTime) + "毫秒");
		}
	}

	private boolean initServer() {
		if (!initLog4j()) {
			return false;
		}

		try {
			ParseServerConf pd = new ParseServerConf();
			pd.createDom();
			System.out.println("初始化服务器运行参数 !");
			pd.parseServerOptions();
			System.out.println("初始化上报数据到中心系统的通信方式 !");
			pd.parseToCenterCommunication();
			System.out.println("初始化从中心系统接收命令的通信方式 !");
			pd.parseFromCenterCommunication();

			System.out.println("初始化短信通讯服务配置<可选> !");
			pd.parseGSMOptions();

			if (ServerContext.toCenterType.equals("dataBase")) {
				System.out.println("远程数据数据库存储，初始化数据源配置 !");
				pd.parseDbConfig();
				pd.getDataSourceName();
			}
			if (ServerContext.toCenterType.equals("servlet")) {
				System.out.println("远程数据Servlet存储!");
				pd.parseDbConfig();
				pd.getDataSourceName();
			}
			System.out.println("初始化存储数据的类 !");
			pd.getSaveDataClass();
			try {
				Class.forName(ServerContext.saveDataClass);
			} catch (Exception e) {
				throw new CommuException().setMessage("产生存储数据的实例"
						+ ServerContext.saveDataClass + "失败!", e);
			}
			if (ServerContext.xmlFileDir.indexOf("\\") >= 0) {
				throw new CommuException()
						.setMessage(
								"Server.xml中元素saveData.xmlFileDir配置中不能有\" \\ \"!",
								null);
			}
			File f = new File(ServerContext.xmlFileDir);
			if ((f == null) || (!f.exists()) || (!f.isDirectory()))
				throw new CommuException().setMessage(
						"Server.xml中元素saveData.xmlFileDir配置的路径不存在!", null);
		} catch (Exception e) {
			Logger log = Logger.getLogger("com.automic.commu.CommuServer");
			log.error(e.getMessage(), e);
			return false;
		}

		try {
			ParseGPRSConf pg = new ParseGPRSConf();
			pg.createDom();
			System.out.println("初始化GPRS协议配置 !");
			pg.parseGPRSProtocolConf();
			System.out.println("初始化测控器协议配置 !");
			pg.parseMeterProtocolConf();
			System.out.println("初始化GPRS配置 !");
			pg.parseGPRSConf();
			System.out.println("初始化GPRS协议解析器驱动 !");
			pg.createGPRSProtocolDriver();
			System.out.println("初始化测控器协议解析器驱动 !");
			pg.createMeterProtocolDriver();
		} catch (Exception ee) {
			Logger log = Logger.getLogger("com.automic.commu.CommuServer");
			log.error(ee.getMessage(), ee);
			return false;
		}

		if (ServerContext.toCenterType.equals("dataBase")) {
			System.out.println("创建数据源 !");
			if (!createDataSource()) {
				Logger log = Logger.getLogger("com.automic.commu.CommuServer");
				log.error("创建数据源失败！");
				System.out.println("创建数据源失败 !");
				return false;
			}
		}

		return true;
	}

	private boolean createDataSource() {
		NcsDataSourceManager obj = NcsDataSourceManager
				.getInstance(ServerContext.dbvos);
		if (obj == null) {
			return false;
		}
		ServerContext.DBSManager = obj;
		return true;
	}

	private boolean initLog4j() {
		try {
			System.out.println("初始化服务器运行日志系统 !");
			URL configFileURL = null;
			configFileURL = CommuServer.class.getResource("/log4j.properties");
			PropertyConfigurator.configure(configFileURL);
			return true;
		} catch (Exception e) {
			System.out.println("通信服务器启动时，初始化log4j日志出错 !");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}

	private static class StartRemoteServerThread extends Thread {
		public void run() {
			RemoteServer s = new RemoteServer();
			s.startServer();
		}
	}

	private class StartLocalServerThread extends Thread {
		private StartLocalServerThread() {
		}

		public void run() {
			LocalServer ss = new LocalServer();
			ss.startServer();
		}
	}

	private class StartGSMServerThread extends Thread {
		private StartGSMServerThread() {
			System.out.println("test");
		}
	}
}
